#!/usr/bin/env bash
set -euo pipefail

dn=$(dirname "$0")
# shellcheck source=src/cmdlib.sh
. "${dn}"/cmdlib.sh

# Initialize FORCE to 0 and BRANCH/INSTALLER_DIR to an empty string
FORCE=0
BRANCH=""

print_help() {
    cat 1>&2 <<'EOF'
Usage: coreos-assembler init --help
       coreos-assembler init [--force] [--branch BRANCH] GITCONFIG [SUBDIR]

  For example, you can use https://gitee.com/anolis/lifsea-config
  as GITCONFIG, or fork it.  Another option useful for local development
  (if you're running a shell inside this container) is to pass a file path
  starting with `/` - a symlink to it will be created and then used directly.
  You can specify a branch of a git repo with the `--branch` flag.

  If specified, SUBDIR is a subdirectory of the git repository that should
  contain manifest.yaml and image.yaml.
EOF
}

# Call getopt to validate the provided input.
rc=0
options=$(getopt --options hfb:i: --longoptions help,force,branch: -- "$@") || rc=$?
[ $rc -eq 0 ] || {
    print_help
    exit 1
}
eval set -- "$options"
while true; do
    case "$1" in
    -h | --help)
        print_help
        exit 0
        ;;
    -f | --force)
        FORCE=1
        ;;
    -b | --branch)
        case "$2" in
            "")
                shift ;;
            *)
                BRANCH="$2"
                shift ;;
        esac
        ;;
    --)
        shift
        break
        ;;
    *)
        print_help
        fatal "init: unrecognized option: $1"
        exit 1
        ;;
    esac
    shift
done

# If user did not provide a repo then error out
if [ $# = 0 ]; then
    print_help
    fatal "ERROR: Missing GITCONFIG"
    exit 1
fi

# If the current working dir is not empty then error out
# unless force provided
if [ "$FORCE" != "1" ] && [ -n "$(ls -A ./)" ]; then
   fatal "init: current directory is not empty, override with --force"
fi

source=$1; shift
subdir=${1:-}

preflight

if has_privileges; then
    sudo chown "$USER:" .
elif [ ! -w . ]; then
    fatal "init: running unprivileged, and current directory not writable"
fi

set -x
# Initialize sources (git)
mkdir -p src
(cd src
 if ! test -e config; then
     case "${source}" in
         /*) ln -s "${source}/${subdir}" config;;
         *) git clone ${BRANCH:+--branch=${BRANCH}} --recurse-submodules "${source}" config
            if [ -n "${subdir}" ]; then
                mv config config-git
                ln -sr config-git/"${subdir}" config
            fi
            (set +x; cd config && echo -n "Config commit: " && git describe --tags --always --abbrev=42)
            ;;
     esac
     manifest=config/manifest.yaml
     if ! [ -f "${manifest}" ]; then
         echo 1>&2 "Failed to find src/${manifest}"
         fatal "If using a custom configuration, be sure it has a manifest.yaml."
     fi
 fi)

mkdir -p cache
mkdir -p builds
mkdir -p tmp
mkdir -p overrides/rpm
mkdir -p overrides/rootfs
